package com.weichen.studentgameexchange.game.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weichen.studentgameexchange.common.common.Result;
import com.weichen.studentgameexchange.common.exception.ServiceException;
import com.weichen.studentgameexchange.game.dao.SortMapper;
import com.weichen.studentgameexchange.game.entity.*;
import com.weichen.studentgameexchange.game.entity.vo.SortVo;
import com.weichen.studentgameexchange.game.entity.vo.UserGenreVo;
import com.weichen.studentgameexchange.game.entity.vo.UserSortVo;
import com.weichen.studentgameexchange.game.service.ISortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 惟尘
 * @since 2025-02-01
 */
@Service
public class SortServiceImpl extends ServiceImpl<SortMapper, Sort> implements ISortService {

    @Autowired
    SortMapper sortMapper;

    private double gradeCount = 0.0;
    /**
     * 新增分类
     *
     * @param sort
     */
    @Override
    public Result adminAdd(Sort sort) {
        String sortName = sort.getSortName();
        if (sortName == null)
            return Result.error("分类名不能为空！");
        Sort one = Db.lambdaQuery(Sort.class)
                .eq(Sort::getSortName, sortName)
                .one();
        if (one != null)
            return Result.error("分类名已存在！");
        sortMapper.insert(sort);
        return Result.success();
    }

    /**
     * 分页查询
     *
     * @param keyword
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Sort> adminPage(String keyword, Integer page, Integer size) {
        Page<Sort> sortPage = new Page<>(page, size);
        LambdaQueryWrapper<Sort> sortLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sortLambdaQueryWrapper
                .orderByDesc(Sort::getSortId)
                .like(keyword != null, Sort::getSortName, keyword);
        Page<Sort> selectPage = sortMapper.selectPage(sortPage, sortLambdaQueryWrapper);
        return selectPage;
    }

    /**
     * 修改分类信息
     *
     * @param sort
     */
    @Override
    public Result adminUpdate(Sort sort) {
        String sortName = sort.getSortName();
        if (StrUtil.isBlankIfStr(sortName))
            return Result.error("分类名不能为空！");
        Sort one = Db.lambdaQuery(Sort.class)
                .eq(Sort::getSortName, sortName)
                .one();
        if (one != null)
            return Result.error("分类名已存在！");
        Long sortId = sort.getSortId();
        if (sortId == null)
            return Result.error("分类Id不能为空！");
        Sort one1 = Db.lambdaQuery(Sort.class)
                .eq(Sort::getSortId, sortId)
                .one();
        if (one1 == null)
            return Result.error("分类不存在！");
        sortMapper.updateById(sort);
        return Result.success();
    }

    /**
     * 单个删除
     *
     * @param sortId
     */
    @Override
    public void adminDeleteOne(Long sortId) {
        if (sortId == null)
            throw new ServiceException("分类Id不能为空！");
        Sort one = Db.lambdaQuery(Sort.class)
                .eq(Sort::getSortId, sortId)
                .one();
        if (one == null)
            throw new ServiceException("分类不存在！");
        Db.lambdaUpdate(GameSort.class)
                .eq(GameSort::getSortId, sortId)
                .remove();
        Db.lambdaUpdate(Sort.class)
                .eq(Sort::getSortId, sortId)
                .remove();
    }

    /**
     * 新增游戏-分类
     *
     * @param sortVo
     */
    @Override
    public Result addGameSort(SortVo sortVo) {
        Sort sort1 = BeanUtil.copyProperties(sortVo, Sort.class);
        String sortName = sortVo.getSortName();
        adminAdd(sort1);
        Sort sort = Db.lambdaQuery(Sort.class)
                .eq(Sort::getSortName, sortName)
                .one();
        List<String> gameNames = sortVo.getGameNames();
        if (gameNames.size() > 0){
            List<Long> gameIds = Db.lambdaQuery(Game.class)
                    .in(Game::getGameName, gameNames)
                    .list()
                    .stream()
                    .map(Game::getGameId)
                    .toList();
            gameIds.forEach(gameId -> {
                GameSort one = Db.lambdaQuery(GameSort.class)
                        .eq(GameSort::getGameId, gameId)
                        .eq(GameSort::getSortId, sort.getSortId())
                        .one();
                if (one == null) {
                    GameSort gameSort = new GameSort();
                    gameSort.setGameId(gameId);
                    gameSort.setSortId(sort.getSortId());
                    Db.save(gameSort);
                }
            });
        }
        return Result.success();
    }

    /**
     * 查看游戏-分类信息
     *
     * @param sortId
     */
    @Override
    public Result selectGameSort(Long sortId) {
        Sort sort = sortMapper.selectById(sortId);
        if (sort == null)
            return Result.error("分类不存在！");
        SortVo sortVo = BeanUtil.copyProperties(sort, SortVo.class);
        List<Long> gameIds = Db.lambdaQuery(GameSort.class)
                .eq(GameSort::getSortId, sortId)
                .list()
                .stream()
                .map(GameSort::getGameId)
                .toList();
        List<String> gameNames = new ArrayList<>();
        if (gameIds.size() > 0) {
            gameNames = Db.lambdaQuery(Game.class)
                    .in(Game::getGameId, gameIds)
                    .list()
                    .stream()
                    .map(Game::getGameName)
                    .toList();
        }
        sortVo.setGameNames(gameNames);
        return Result.success(sortVo);
    }

    /**
     * 修改游戏-分类信息
     *
     * @param sortVo
     */
    @Override
    public Result updateGameSort(SortVo sortVo) {
        String sortName = sortVo.getSortName();
        if (StrUtil.isBlankIfStr(sortName))
            return Result.error("分类名不能为空！");
        Sort sort = Db.lambdaQuery(Sort.class)
                .eq(Sort::getSortName, sortName)
                .one();
        Long sortId = sortVo.getSortId();
        if (sortId == null)
            return Result.error("分类Id不能为空！");
        Sort one1 = Db.lambdaQuery(Sort.class)
                .eq(Sort::getSortId, sortId)
                .one();
        if (one1 == null)
            return Result.error("分类不存在！");
        if (sort != null && !one1.getSortName().equals(sortName))
            return Result.error("分类名已存在！");
        Sort sort1 = BeanUtil.copyProperties(sortVo, Sort.class);
        List<String> gameNames = sortVo.getGameNames();
        Db.lambdaUpdate(GameSort.class)
                .eq(GameSort::getSortId, sortId)
                .remove();
        if (gameNames.size()>0){
            List<Long> gameIds = Db.lambdaQuery(Game.class)
                    .in(Game::getGameName, gameNames)
                    .list()
                    .stream()
                    .map(Game::getGameId)
                    .toList();
            List<GameSort> gameSorts = gameIds.stream().map(gameId -> {
                GameSort gameSort = new GameSort();
                gameSort.setSortId(sortId);
                gameSort.setGameId(gameId);
                return gameSort;
            }).toList();
            Db.saveBatch(gameSorts);
        }
        sortMapper.insertOrUpdate(sort1);

        return Result.success();
    }

    @Override
    public Result userPage(Long sortId, Integer page, Integer size) {
        List<Long> gameIds = Db.lambdaQuery(GameSort.class)
                .eq(GameSort::getSortId, sortId)
                .list()
                .stream()
                .map(GameSort::getGameId)
                .toList();
        if (gameIds.size() ==0)
            return Result.error("没有对应的游戏");
        if (sortId == 2L)
            gameIds = Db.lambdaQuery(GameVersion.class)
                    .in(GameVersion::getGameId, gameIds)
                    .orderByDesc(GameVersion::getReleaseDate)
                    .list()
                    .stream()
                    .map(GameVersion::getGameId)
                    .toList();
        List<Game> games = gameIds.stream().map(gameId -> Db.lambdaQuery(Game.class)
                .eq(Game::getGameId, gameId)
                .one()).toList();
        List<UserSortVo> vos =new ArrayList<>();
        games.forEach(game -> {
            gradeCount = 0.0;
            UserSortVo vo = BeanUtil.copyProperties(game, UserSortVo.class);
            int count = Db.lambdaQuery(UserGameCollection.class)
                    .eq(UserGameCollection::getGameId, game.getGameId())
                    .list()
                    .size();
            vo.setCollectionCount(count);
            List<UserGameGrade> list = Db.lambdaQuery(UserGameGrade.class)
                    .eq(UserGameGrade::getGameId, game.getGameId())
                    .list();
            if (list.size()>0){
                List<BigDecimal> bigDecimals = list.stream().map(UserGameGrade::getGradeScore).toList();
                bigDecimals.forEach(bigDecimal -> {
                    double v = bigDecimal.doubleValue();
                    gradeCount = gradeCount + v;
                });
                gradeCount = gradeCount/(list.size());
            }
            vo.setGradeCount(gradeCount);
            vos.add(vo);
        });
        Page<UserSortVo> sortVoPage = new Page<>(page,size);
        sortVoPage.setRecords(vos);
        return Result.success(sortVoPage);
    }
}
